using MultiAgentsClient.ChatDataStructures;
using MultiAgentsClient.Manager;
using MultiAgentsClient.Service;
using MultiAgentsClient.Manager.DataModel;
using MultiAgentsClient.Service.SignalRService;
using MultiAgentsShared;
using Window = Microsoft.UI.Xaml.Window;
using Microsoft.UI.Xaml.Navigation;

namespace MultiAgentsClient;

public class App : Application
{
    private NavigationManager? navigationManager;
    protected Window? MainWindow { get; private set; }
    protected IHost? Host { get; private set; }
    public IServiceProvider? ServiceProvider { get; private set; }

    protected override async void OnLaunched(LaunchActivatedEventArgs args)
    {
        //ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(320, 200));
        IApplicationBuilder builder = this.CreateBuilder(args)
            .Configure(host => host
#if LOCALDEV
                .UseEnvironment(Environments.Development)
#endif
                .UseLogging(configure: (context, logBuilder) =>
                {
                    logBuilder
                        .SetMinimumLevel(
                            context.HostingEnvironment.IsDevelopment() ?
                                LogLevel.Information :
                                LogLevel.Warning)

                        .CoreLogLevel(LogLevel.Warning);
                }, enableUnoLogging: true)
                .ConfigureServices((context, services) =>
                {
                    services.AddHttpClient();

                    // managers
                    services.AddSingleton<MessageManager>();
                    services.AddSingleton<MessageWebviewOperator>();
                    services.AddSingleton<ProjectManager>();
                    services.AddSingleton<SystematicNotificationManager>();
                    services.AddSingleton<UserInfoManager>();
                    services.AddSingleton<WorkflowManager>();
                    services.AddSingleton<WorkflowOperator>();
                    services.AddSingleton<WorkflowWebviewOperator>();
                    services.AddSingleton<AutoUpdateOperator>();
                    services.AddSingleton<AutoLoginManager>();
                    services.AddSingleton<AgentManager>();
                    services.AddSingleton<LocalDataOperator>();

                    // services
                    services.AddSingleton<SignalRChatService>();
                    services.AddSingleton<SignalRUserService>();
                    services.AddSingleton<SignalRWorkflowService>();
                    services.AddSingleton<SignalRUserSettingsService>();
                    services.AddSingleton<SignalRAgentService>();
                    services.AddSingleton<GitlabService>();
                    services.AddSingleton<AppConfigService>();
                    services.AddTransient<VisualStudioPrjBuilderService>();
                    services.AddTransient<ClientToolCallerService>();
                    services.AddTransient<SqliteService>();

                    // data models
                    services.AddSingleton<UserDataModel>();
                    services.AddSingleton<SystemConfigDataModel>();
                    services.AddSingleton<WorkflowDataModel>();
                    services.AddSingleton<SystematicNotificationDataModel>();

                    // tools
                    services.AddSingleton<ToolSetCollection>();
                    services.AddTransient<MatlabControlToolProvider>();

                    //this serviceProvider needs to be bottom so it collects all the registration before this line
                    ServiceProvider = services.BuildServiceProvider();
                    var loggerFactory = ServiceProvider.GetRequiredService<ILoggerFactory>();
                    var logger = loggerFactory.CreateLogger<Debug>();
                    Debug.Init(logger);

                    ServiceProvider.GetService<SignalRChatService>();
                    ServiceProvider.GetService<SignalRUserService>();
                    ServiceProvider.GetService<SignalRUserSettingsService>();
                    ServiceProvider.GetService<SignalRWorkflowService>();
                    ServiceProvider.GetService<SignalRAgentService>();
                })
        );

        MainWindow = builder.Window;

        Host = builder.Build();

        Frame rootFrame = MainWindow.Content as Frame ?? new();

        MainWindow.Content = rootFrame;

        navigationManager = new NavigationManager(rootFrame);

        MainWindow.Activate();

        if (ServiceProvider != null)
        {
            //force instance of MessageHandlerService
            AutoUpdateOperator? autoUpdateOperator = ServiceProvider.GetService<AutoUpdateOperator>();
            if (autoUpdateOperator != null)
            {
#if !LOCALDEV
                if (await autoUpdateOperator.CheckHasNewVersion())
                {
                    rootFrame.Navigate(typeof(UpdatePage), args.Arguments);
                    await autoUpdateOperator.UpdateProject();
                }
                else
                {
                    _ = autoUpdateOperator.KeepCheckNewVersion();
                }
#endif
            }

            try
            {
                ServiceProvider.GetService<UserInfoManager>();
                AutoLoginManager? autoLoginManager = ServiceProvider.GetService<AutoLoginManager>();
                if (autoLoginManager != null)
                {
                    _ = autoLoginManager.LoginAutoRequest();
                }

                ServiceProvider.GetService<MessageManager>();
                ServiceProvider.GetService<MessageWebviewOperator>();
                ServiceProvider.GetService<ProjectManager>();
                ServiceProvider.GetService<SystematicNotificationManager>();
                ServiceProvider.GetService<WorkflowManager>();
                ServiceProvider.GetService<WorkflowOperator>();
                ServiceProvider.GetService<WorkflowWebviewOperator>();
                ServiceProvider.GetService<AgentManager>();
                ServiceProvider.GetService<LocalDataOperator>();

                ServiceProvider.GetService<ToolSetCollection>();
                ServiceProvider.GetService<GitlabService>();
                ServiceProvider.GetService<ClientToolCallerService>();
            }
            catch (Exception ex)
            {
                Debug.LogError($"初始化错误:{ex.Message}");
            }

            rootFrame.Navigate(typeof(LoginPage), args.Arguments);

            NavigationManager.CurrentPage = typeof(LoginPage);
        }
    }
}
